package topic;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import org.junit.Test;
import util.ConnUtil;

import java.io.IOException;

/**
 * 可以指定不同的RoutingKey，让交换机根据RoutingKey的不同，将消息路由到不同的队列中，并且RoutingKey可以指定通配符和占位符，必须按照[aa.bb.cc.xx.yy.zz]()规则去编写，用[.]()隔开
 * @author TZL
 * @date 2020/8/14
 */
public class Publisher {

    public static final String EXCHANGE_NAME = "topic";
    public static final String ORANGE_QUEUE = "orange-queue";
    public static final String LAZY_RABBIT_QUEUE = "lazy-rabbit-queue";

    @Test
    public void publish() throws Exception {
        //1. Conn
        Connection conn = ConnUtil.getConn();
        //2. Channel
        Channel channel = conn.createChannel();


        //3.1 创建Exchange
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC,true,false,null);
        //3.2 创建Queue1
        channel.queueDeclare(ORANGE_QUEUE,true,false,false,null);
        //3.3 创建Queue2
        channel.queueDeclare(LAZY_RABBIT_QUEUE,true,false,false,null);
        //3.4 queue1绑定到exchange
        channel.queueBind(ORANGE_QUEUE,EXCHANGE_NAME,"*.orange.*");
        //3.5 queue2绑定到exchange
        channel.queueBind(LAZY_RABBIT_QUEUE,EXCHANGE_NAME,"*.*.rabbit");
        channel.queueBind(LAZY_RABBIT_QUEUE,EXCHANGE_NAME,"lazy.#");

        //4. 发送消息到exchange,指定routingKey
        String bigOrangeRabbitMsg = "大橙兔！！！";
        channel.basicPublish(EXCHANGE_NAME,"big.orange.rabbit",null,bigOrangeRabbitMsg.getBytes());

        String lazyBlackPig = "懒黑猪!!!";
        channel.basicPublish(EXCHANGE_NAME,"lazy.black.pig",null,lazyBlackPig.getBytes());

        //5. close
        channel.close();
        conn.close();
    }

}
